//
//  MTSeriBleTalkViewController.swift
//  MTBLETools
//
//  Created by 方强 on 16/10/11.
//  Copyright © 2016年 MT. All rights reserved.
//

import UIKit
import MTSDK

class MTSeriBleTalkViewController: UIViewController, UITableViewDataSource, UIActionSheetDelegate{

    class func getActivity() -> MTSeriBleTalkViewController{
        let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main);
        let vc = storyBoard.instantiateViewController(withIdentifier: "MTSeriBleTalkViewController") as! MTSeriBleTalkViewController;
        
        return vc;
    }
    
    var working_device: MTBLEDevice!;
    var msg_list: [String] = [];
    override func viewDidLoad() {
        super.viewDidLoad()

        getDatas();
        
        initView();
        
        initBLE();
        
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(keyboardHide));
        tapGestureRecognizer.cancelsTouchesInView = false;
        self.view.addGestureRecognizer(tapGestureRecognizer);
    }
    
    func keyboardHide(tap:UITapGestureRecognizer){
        self.view.endEditing(true);
    }
    
    // 获取全局数据
    private var mStaticDatas: StaticDatas!;
    private func getDatas(){
        mStaticDatas = StaticDatas.getInstance();
    }
    
    // 初始化控件
    private var baseAlert: UIAlertView!;
    @IBOutlet weak var data_edit: UITextField!
    @IBOutlet weak var msg_listview: UITableView!
    @IBOutlet weak var recivetype_btn: UIBarButtonItem!
    @IBOutlet weak var connect_btn: UIBarButtonItem!
    @IBOutlet weak var translatetype_btn: UIBarButtonItem!
    @IBOutlet weak var sendtype_btn: UIButton!
    private var recivetype_actionsheet: UIActionSheet!;
    private var sendtype_actionsheet: UIActionSheet!;
    private var talktype_actionsheet: UIActionSheet!;
    private var recivetype_index: Int = 0;
    private var sendtype_index: Int = 0;
    private var talktype_index: Int = 0;
    private func initView(){
        msg_listview.dataSource = self;
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return msg_list.count;
    }
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let msgcell = UITableViewCell();
        
        msgcell.textLabel?.text = self.msg_list[indexPath.row];
        
        return msgcell;
    }
    
    // 选择回调
    private let DataType = ["Str","16"];
    private let TalkType = ["透传", "命令"];
    public func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int){
        if(buttonIndex == 0){
            return;
        }
        
        if(actionSheet === self.recivetype_actionsheet){
            recivetype_index  = buttonIndex-1;
            recivetype_btn.title = DataType[recivetype_index];
            return;
        }
        
        if(actionSheet === self.sendtype_actionsheet){
            sendtype_index  = buttonIndex-1;
            sendtype_btn.setTitle(DataType[sendtype_index], for: UIControlState.normal);
            return;
        }
        
        if(actionSheet === self.talktype_actionsheet){
            talktype_index = buttonIndex-1;
            translatetype_btn.title = TalkType[talktype_index];
            return;
        }
    }
    
    @IBAction func itemOnclick(_ sender: UIBarButtonItem) {
        
        if(sender.tag == 1){    // 返回
            mble.disConnect();
            self.dismiss(animated: false, completion: { 
                
            });
            return;
        }
        
        if(sender.tag == 2){    // 接收数据格式
            recivetype_actionsheet = UIActionSheet(title: "接收数据格式", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil);
            for i in DataType{
                recivetype_actionsheet.addButton(withTitle: i);
            }
            recivetype_actionsheet.show(in: self.view);
            
            return;
        }
        
        if(sender.tag == 3){    // 连接/断开
            if(mble.isMTSericonnect()){  // 如果已经连接，则断开连接
                mble.disConnect();
            }else{
                startConnect();
            }
            return;
        }
        
        if(sender.tag == 4){    // 清空接收
            msg_list.removeAll();
            msg_listview.reloadData();
            return;
        }
        
        if(sender.tag == 5){    // 透传/命令切换
            talktype_actionsheet = UIActionSheet(title: "模式选择", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil);
            for i in TalkType{
                talktype_actionsheet.addButton(withTitle: i);
            }
            talktype_actionsheet.show(in: self.view);
            return;
        }
    }
    @IBAction func btnOnclick(_ sender: UIButton) {
        if(sender.tag == 1){   //
            sendtype_actionsheet = UIActionSheet(title: "发送格式", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil);
            for i in DataType{
                sendtype_actionsheet.addButton(withTitle: i);
            }
            sendtype_actionsheet.show(in: self.view);
            return;
        }
        
        if(sender.tag == 2){   // 发送按钮
            let datas = getEditDatas();
            if(datas == nil){
                return;
            }
            
            if(talktype_index == 0){
                mble.addWriteDatasAction(action: WriteCharactAction(charact: nil, datas: datas, option: self.actionOption));
            }else if(talktype_index == 1){
                let action = WriteCharactWithAckAction(sendCharact: nil, reviceCharact: nil, datas: datas, option: self.actionOption);
                action.onReciveDatas = { (action, charact, data) in
                    action.setStatues(statues: BLEBaseAction_ActionStatues.DONE);
                    self.msg_list.append(String(data: data!, encoding: String.Encoding.utf8)!);
                    self.msg_listview.reloadData();
                };
                mble.addCmdAction(action: action);
            }
            
            msg_list.append(data_edit.text!);
            self.msg_listview.reloadData();
            
            return;
        }
    }
    
    // 初始化蓝牙
    var mble: MTSeriaBase!;
    var bleCallback: MTSeria_Callback!;
    private var actionOption: BLEBaseAction_ActionOption!;
    private func initBLE(){
        mble = MTSeriaBase(manager: MTBLEManager.getInstance()!);
        actionOption = BLEBaseAction_ActionOption(timeout: 1000);
        
        bleCallback = MTSeria_Callback();
        bleCallback.onConnect = self.onConnect;
        bleCallback.reTryConnect = self.reTryConnect;
        bleCallback.onDisConnect = self.onDisConnect;
        bleCallback.onManualDisConnect = self.onManualDisConnect;
        bleCallback.onDatasRecive = self.onDatasRecive;
        bleCallback.onCmdRevice = self.onCmdRevice;
        
        startConnect();
    }
    
    // 连接蓝牙
    private func startConnect(){
        self.baseAlert = UIAlertView(title: "Inf", message: "连接。。。", delegate: nil, cancelButtonTitle: nil);  // 建立一个缓冲对话框
        self.baseAlert.show();
        let errocode = mble.connect(device: working_device, callback2: bleCallback, retryTime: 2);
        
        if(errocode?.getCode() != 0){
            self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
            self.showFailAlert(erromsg: "连接失败");
        }
    }
    
    // 显示失败对话框
    private func showFailAlert(erromsg: String){
        baseAlert = UIAlertView(title: "Fail", message: erromsg, delegate: nil, cancelButtonTitle: "OK");
        baseAlert.show();
    }
    
    // 链接回调
    private func onConnect(ble:MTSeriaBase, errocode:ErroCode){
        self.baseAlert.dismiss(withClickedButtonIndex: 0, animated: false);
        if(errocode.getCode() != 0){
            print("连接失败->\(errocode.getMsg())");
            return;
        }
        self.connect_btn.title = "断开";
    }
    // 尝试重连
    private func reTryConnect(ble:MTSeriaBase, retry: Int){
    
    }
    // 被动断开链接
    private func onDisConnect(ble:MTSeriaBase, errocode:ErroCode){
        self.connect_btn.title = "连接";
    }
    // 主动断开链接
    private func onManualDisConnect(ble:MTSeriaBase, errocode:ErroCode){
        self.connect_btn.title = "连接";
    }
    // 接收到数据
    private func onDatasRecive(ble:MTSeriaBase, datas:Data?){
        if(recivetype_index == 0){  // 字符串接收
            msg_list.append(String(data: datas!, encoding: String.Encoding.utf8)!);
            msg_listview.reloadData();
            return;
        }
        
        if(recivetype_index == 1){  // 16进制接收
            msg_list.append(MTTools.convertBytearrayToString(data: MTTools.converDataToByteArray(data: datas!))!);
            msg_listview.reloadData();
            return;
        }
    }
    // 接收到命令
    private func onCmdRevice(ble:MTSeriaBase, datas:Data?){
        
    }
    
    // 获取编辑数据
    private func getEditDatas() -> Data?{
        
        var datas: Data?;
        
        if(sendtype_index == 0){  // String格式发送
            datas = self.data_edit.text?.data(using: String.Encoding.utf8);
            return datas;
        }
        
        if(sendtype_index == 1){  // 16进制格式发送
            datas = MTTools.convertStringToByteArray(str: self.data_edit.text!);
            return datas;
        }
        
        return datas;
    }
    
    // 接收到的数据，转换成指定格式

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func TextFinish(_ sender: UITextField) {
        sender.resignFirstResponder();
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        self.view.openKeyboardOffsetView();
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated);
        self.view.closeKeyboardOffsetView();
    }
    
}
